package com.bxw.forum.controller;


import com.bxw.forum.common.AppResult;
import com.bxw.forum.common.ResultCode;
import com.bxw.forum.config.AppConfig;
import com.bxw.forum.exception.ApplicationException;
import com.bxw.forum.model.User;
import com.bxw.forum.service.IUserService;
import com.bxw.forum.utils.MD5Utils;
import com.bxw.forum.utils.StringUtils;
import com.bxw.forum.utils.UUIDUtils;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private IUserService userService;

    /**
     * 注册
     * @param username 用户名
     * @param password 用户密码
     * @param nickname 昵称
     * @param passwordRepeat 第二次密码
     * @return
     */
    @RequestMapping("/register")
    public AppResult register(@RequestParam("username") @NonNull String username,
                              @RequestParam("password") @NonNull String password,
                              @RequestParam("nickname") @NonNull String nickname,
                              @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {

        //1，参数校验(非空校验)
        //密码确认
        //2，生成User类
        //设置参数
        //生密码
        //3，调用service层创建


        if(!password.equals(passwordRepeat)) {

            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            return AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        User user = new User();

        user.setUsername(username);
        user.setNickname(nickname);

        String salt = UUIDUtils.UUID_32();
        String ciphertext = MD5Utils.md5Salt(password,salt);
        user.setPassword(ciphertext);
        user.setSalt(salt);

        userService.createNormalUser(user);

        return AppResult.success();

    }

    /**
     * 登录
     * @param username 用户名
     * @param password 用户密码
     * @param request 客户端请求
     * @return
     */
    @RequestMapping("/login")
    public AppResult login(@RequestParam("username") @NonNull String username,
                           @RequestParam("password") @NonNull String password,
                           HttpServletRequest request) {
        //1，参数校验(非空校验)
        //2，调用service判断是否存在存在该用户或者密码是否正确


        User user = userService.login(username,password);

        if(user == null) {

            log.warn(ResultCode.FAILED_LOGIN.toString());

            return AppResult.fail(ResultCode.FAILED_LOGIN);
        }


//        HttpSession existSession = request.getSession(false);
//        System.out.println("------------有session则去创建，没有则不去主动创建-----------------");
// || existSession.getAttribute(AppConfig.USER_SESSION) != null
//        if(existSession != null) {
//
//            System.out.println("-------------判断session存在,从已存在的session中获取对象-------------------");
//            User existUser = (User) existSession.getAttribute(AppConfig.USER_SESSION);
//            if(existUser == null) {
//                return AppResult.fail("清空后台重试");
//            }
//            System.out.println("-------------从session中获取user对象：" + existUser.toString() + "-----------------");
//            System.out.println("-------------从参数中获取user对象：" + user.toString() + "-----------------");
//            if(user.getId().equals(existUser.getId())) {
//                System.out.println("--------------登录用户与已存在的用户是同一用户----------------");
//                log.warn("重复登录" + "要登录的用户名：" + username + "已登录的用户名" + existUser.getUsername());
//
//                return AppResult.fail("已登录，请退出登录后重试");
//            }else {
//                System.out.println("--------------登录用户与已存在的用户是不是同一用户,创建session会话----------------");
//
//                HttpSession session = request.getSession(true);
//                session.setAttribute(AppConfig.USER_SESSION,user);
//            }
//
//        }else {
//            System.out.println("-------------判断session不存在,创建session会话-------------------");
//
//            HttpSession session = request.getSession(true);
//            session.setAttribute(AppConfig.USER_SESSION,user);
//        }


        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);

        return AppResult.success(ResultCode.SUCCESS);

    }

    /**
     * 获取个人信息
     * @param request 客户端请求
     * @param id 用户ID
     * @return
     */
    @RequestMapping("/info")
    public AppResult<User> info(HttpServletRequest request,
                                @RequestParam(value = "id",required = false)Long id) {

        //1，判断是否传入id
        //没传->通过request去获取session，根据session中的user返回给前端
        //传入->通过service接口根据id去查询user

        User user = null;

        if(id == null) {
            HttpSession session = request.getSession(false);


            user = (User) session.getAttribute(AppConfig.USER_SESSION);

//            if (session == null || session.getAttribute(AppConfig.USER_SESSION) == null) {
//
//                log.warn(ResultCode.FAILED_FORBIDDEN.toString() + "在id为null的情况下因为没有登录导致无法访问");
//
//                return AppResult.fail(ResultCode.FAILED_FORBIDDEN);
//
//            }else {
//
//                user = (User) session.getAttribute(AppConfig.USER_SESSION);
//
//            }
        }else {
            user = userService.selectById(id);

            log.info("未登录情况下通过id获取用户信息");
        }



        if(user == null) {

            log.warn(ResultCode.FAILED_FORBIDDEN.toString() + "查到用户信息为null");

            return AppResult.fail(ResultCode.FAILED_FORBIDDEN);

        }

        return AppResult.success(user);
    }

    /**
     * 退出登录
     * @param request 客户端请求
     * @return AppResult
     */
    @RequestMapping("/loginout")
    public AppResult loginout(HttpServletRequest request) {

        HttpSession session = request.getSession(false);

        if(session != null) {

            log.info("退出登录");
            session.invalidate();

        }

        return AppResult.success();
    }

    @RequestMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @RequestParam(value = "username",required = false) String username,
                                @RequestParam(value = "nickname",required = false) String nickname,
                                @RequestParam(value = "gender",required = false) Byte gender,
                                @RequestParam(value = "email",required = false) String email,
                                @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                @RequestParam(value = "remark",required = false) String remark) {

        // 1. 接收参数
        // 2. 对参数做非空校验（全部都为空，则返回错误描述）
        if (StringUtils.isEmpty(username) && StringUtils.isEmpty(nickname)
                && StringUtils.isEmpty(email) && StringUtils.isEmpty(phoneNum)
                && StringUtils.isEmpty(remark) && gender == null) {
            // 返回错误信息
            return AppResult.fail("请输入要修改的内容");
        }

        // 从session中获取用户Id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 3. 封装对象
        User updateUser = new User();
        updateUser.setId(user.getId()); // 用户Id
        updateUser.setUsername(username); // 用户名
        updateUser.setNickname(nickname); // 昵称
        updateUser.setGender(gender); // 性别
        updateUser.setEmail(email); // 邮箱
        updateUser.setPhoneNum(phoneNum); // 电话
        updateUser.setRemark(remark); // 个人简介

        // 4. 调用Service中的方法
        userService.modifyInfo(updateUser);
        // 5. 查询最新的用户信息
        user = userService.selectById(user.getId());
        // 6. 把最新的用户信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION, user);
        // 7. 返回结果
        return AppResult.success(user);
    }

    @RequestMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @RequestParam("newPassword") @NonNull String newPassword,
                                    @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {

        //从request中获取session.
        //从session中获取user对象
        //校验newPassword和passwordRepeat
        //调用Service修改密码
        //成功将session失效
        //返回结果


        // 1. 校验新密码与确认密码是否相同
        if (!newPassword.equals(passwordRepeat)) {
            // 返回错误描述
            return AppResult.fail(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 2. 获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 3. 调用Service
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
        // 4. 销毁session
        if (session != null) {
            session.invalidate();
        }
        // 5. 返回结果
        return AppResult.success();

    }
}
